<template>
	<div class="container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<div class="search-input">
				<text class="iconfont icon-sousuo"></text>
				<input type="text" v-model="searchKeyword" placeholder="搜索企业名称" />
			</div>
		</div>

		<!-- 绑定企业按钮 -->
		<div class="bind-company-btn" @click="scanQrCode">
			<div class="bind-icon">
				<div class="icon-group">
					<text class="iconfont icon-qrcode"></text>
				</div>
			</div>
			<div class="bind-text">扫一扫绑定</div>
		</div>

		<!-- 已绑定企业列表 -->
		<div class="company-list-container">
			<div class="company-list-title">已绑定企业列表 ({{ channelInfo.enterprise_count || 0 }})</div>

			<div class="company-list" v-if="filteredCompanies.length > 0">
				<div class="company-item" v-for="(company, index) in filteredCompanies" :key="company.enterprise_id">
					<div class="company-header" @click="toggleCompanyProjects(index)">
						<div class="company-icon" :class="{ disabled: company.status === 0 }">
							<i class="iconfont icon-qiye"></i>
						</div>
						<div class="company-info">
							<div class="company-name-container">
								<div class="company-name">{{ company.name }}</div>
								<div class="status-tag" v-if="company.status === 0">已禁用</div>
							</div>
							<div class="project-count">项目数量: {{ company.project_count || 0 }}</div>
						</div>
						<text
							style="color: #aaa"
							class="iconfont"
							:class="[company.expanded ? 'icon-shouqi' : 'icon-zhankai']"
						></text>
					</div>

					<!-- 项目列表 (展开时显示) -->
					<div class="project-list" v-if="company.expanded">
						<!-- 加载中状态 -->
						<div class="loading-projects" v-if="company.loading">
							<div class="loading-spinner"></div>
							<div class="loading-text">加载中...</div>
						</div>

						<div class="project-item" v-for="project in company.projects" :key="project.project_id" v-else>
							<!-- 新增：项目头部信息容器，包含名称和状态 -->
							<div class="project-header">
								<div class="project-name">
									<view class="name-content">
										{{ project.project_name }}
									</view>
								</div>
								<div class="project-people">
									<span
										style="margin-right: 2vw; font-size: 22rpx"
										:class="[
											'tag-type-' +
												$utils.getConstantItemByVal('projectStatus', project.status).elType
										]"
									>
										{{ $utils.getConstantItemByVal('projectStatus', project.status).label }}
									</span>
									<text>已邀请: {{ project.invited }}人</text>
								</div>
							</div>
							<div class="project-actions">
								<view class="btn-action btn-generate" @click="generateQrCode(project.project_id)">
									生成二维码
								</view>
								<view
									class="btn-action btn-record"
									@click="viewInviteRecords(company.enterprise_id, project.project_id)"
								>
									邀请记录
								</view>
								<view
									class="btn-action btn-detail"
									@click="viewProjectDetail(company.enterprise_id, project.project_id)"
								>
									查看详情
								</view>
							</div>
						</div>
						<div class="empty-projects" v-if="company.projects.length === 0 && !company.loading">
							<div class="empty-text">暂无项目</div>
						</div>
					</div>
				</div>
			</div>

			<div class="empty-list" v-else>
				<div class="empty-icon">
					<img :src="nodata" />
				</div>
				<div class="empty-text">暂无匹配的企业</div>
			</div>
		</div>

		<!-- 二维码弹窗 -->
		<div class="qrcode-modal" v-if="showQrCode">
			<div class="modal-mask" @click="closeQrCode"></div>
			<div class="modal-content">
				<div class="modal-title">项目邀请二维码</div>
				<div class="qrcode-info" v-if="currentProject">
					<div class="project-name">{{ currentProject.project_name }}</div>
					<div class="enterprise-name">{{ currentProject.enterprise_name }}</div>
				</div>
				<div class="qrcode-box">
					<image :src="qrCodeUrl" mode="aspectFit"></image>
				</div>
				<div class="qrcode-tips">请让员工扫描此二维码加入项目</div>
				<div class="modal-actions">
					<div class="action-btn cancel" @click="closeQrCode">关闭</div>
					<div class="action-btn confirm" @click="saveQrCode">保存图片</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import _ from 'lodash';
export default {
	name: 'HomePage',
	data() {
		return {
			nodata: require('@/static/img/nodata.png'),

			searchKeyword: '',
			channelInfo: {
				name: '',
				mobile: '',
				enterprise_count: 0,
				project_count: 0
			},
			inviteStats: {
				total: 0,
				approved: 0
			},
			companies: [],
			isLoading: false,
			// 防抖标记，避免重复加载
			enterpriseListLoaded: false,
			showQrCode: false, // 是否显示二维码弹窗
			qrCodeUrl: '', // 二维码URL
			currentProject: null // 当前选中的项目
		};
	},
	computed: {
		filteredCompanies() {
			if (!this.searchKeyword) {
				return this.companies;
			}

			const keyword = this.searchKeyword.toLowerCase();
			return this.companies.filter((company) => company.name.toLowerCase().includes(keyword));
		}
	},
	onLoad(e) {
		// 扫码进入本小程序,快速绑定企业
		if (e.scene) {
			let scene = decodeURIComponent(e.scene);
			let code_keyword =
				scene && scene.indexOf('=') != -1 && scene.split('=').length >= 2 ? scene.split('=')[1] : '';
			if (code_keyword) {
				// 设置邀请状态:待邀请
				uni.setStorageSync('inviteComp', {
					keyword: code_keyword,
					invited: false // 待邀请
				});
			}
		}

		// 检查登录状态
		if (!this.checkLogin()) {
			uni.redirectTo({
				url: '/pages/login'
			});
			return;
		}

		// 加载页面数据
		this.loadData();
	},
	onShow() {
		// 每次页面显示时检查是否需要重新加载数据
		if (this.checkLogin() && !this.enterpriseListLoaded) {
			this.loadData(() => {
				// 如果是扫码进入小程序
				let inviteComp = uni.getStorageSync('inviteComp');
				if (inviteComp) {
					// 还没有接受企业邀请
					if (!inviteComp.invited) {
						// 绑定企业
						this.joinComp(inviteComp.keyword);
						return;
					}
				}
			});
		}
	},
	onPullDownRefresh() {
		// 下拉刷新
		this.loadData(() => {
			uni.stopPullDownRefresh();
		});
	},
	methods: {
		// 检查登录状态
		checkLogin() {
			const token = uni.getStorageSync('token');
			return !!token;
		},

		// 加载页面数据
		loadData(callback) {
			if (this.isLoading) {
				if (typeof callback === 'function') {
					callback();
				}
				return;
			}

			this.isLoading = true;

			// 加载渠道信息
			this.getChannelInfo();

			// 加载邀请统计
			this.getInviteStatistics();

			// 加载企业列表
			this.getEnterpriseList(() => {
				this.isLoading = false;
				if (typeof callback === 'function') {
					callback();
				}
			});
		},

		// 获取渠道信息
		getChannelInfo() {
			this.$request.info({}, (res) => {
				this.channelInfo = res;
				// 保存到本地存储
				uni.setStorageSync('channelInfo', {
					name: this.channelInfo.name,
					mobile: this.channelInfo.mobile
				});
			});
		},

		// 获取邀请统计
		getInviteStatistics() {
			this.$request.inviteStatistics({}, (res) => {
				this.inviteStats = res.summary || {
					total: 0,
					approved: 0
				};
			});
		},

		// 获取企业列表
		getEnterpriseList(callback) {
			this.$request.enterpriseList(
				{},
				(res) => {
					// 转换后端数据格式为前端所需格式
					this.companies = (res.list || []).map((item) => ({
						enterprise_id: item.enterprise_id,
						name: item.name,
						logo: item.logo,
						enterprise_type: item.enterprise_type,
						contact_name: item.contact_name,
						contact_mobile: item.contact_mobile,
						bind_time: item.bind_time,
						project_count: item.project_count || 0,
						status: 1, // 假设1为启用，0为禁用
						expanded: false, // 添加展开状态属性
						loading: false, // 添加加载状态属性
						projects: [] // 用于存储项目列表
					}));

					// 标记企业列表已加载
					this.enterpriseListLoaded = true;
				},
				(err) => {},
				() => {
					if (typeof callback === 'function') {
						callback();
					}
				}
			);
		},

		// 绑定企业
		// keyword: 项目id_类型(1员工邀请 2渠道邀请 3渠道邀请员工)
		joinComp(keyword = '') {
			let params = {
				jump_url: 'pages/index',
				type: 1, // 1二维码 2邀请码
				keyword: keyword
			};
			// 获取待绑定的企业名称
			this.$request.getCompanyNameWhichBeBinded(params, (res) => {
				uni.showModal({
					title: '温馨提示',
					content: `是否确认绑定企业【${res.name}】？`,
					confirmText: '确定',
					cancelText: '暂不绑定',
					success: (res) => {
						if (res.confirm) {
							// 设置邀请状态:已邀请
							uni.setStorageSync('inviteComp', {
								keyword: keyword,
								invited: true // 已邀请
							});
							this.$request.bindCompany(params, (res) => {
								uni.showToast({
									title: '企业绑定成功',
									icon: 'none',
									mask: true,
									duration: 2000
								});
								setTimeout(() => {
									this.loadData();
								}, 1500);
							});
						}
					}
				});
			});
		},

		// 切换企业项目列表的展开/折叠状态
		toggleCompanyProjects(index) {
			const isExpanded = !this.companies[index].expanded;

			// 先设置展开状态
			this.$set(this.companies[index], 'expanded', isExpanded);

			// 如果是展开状态且还没有加载过项目，则加载项目列表
			if (isExpanded && this.companies[index].projects.length === 0) {
				// 先设置加载状态
				this.$set(this.companies[index], 'loading', true);

				// 加载项目列表
				this.getCompanyProjects(this.companies[index].enterprise_id, index);
			}
		},

		// 获取企业项目列表
		getCompanyProjects(enterpriseId, companyIndex) {
			this.$request.projectList(
				{
					enterprise_id: enterpriseId
				},
				(res) => {
					// 提取企业和项目信息
					const enterprises = res.list || [];
					// 找到当前企业ID的数据
					const enterprise = enterprises.find((e) => e.enterprise_id === enterpriseId);
					if (enterprise && enterprise.projects) {
						// 更新特定企业的项目列表
						this.$set(
							this.companies[companyIndex],
							'projects',
							enterprise.projects.map((item) => ({
								project_id: item.project_id,
								project_name: item.project_name,
								project_date: item.project_date,
								age_limit: item.age_limit,
								mode: item.mode,
								is_online_contract: item.is_online_contract,
								status: item.project_status,
								assign_time: item.assign_time,
								enterprise_id: enterpriseId,
								enterprise_name: enterprise.enterprise_name,
								invited: item.invite_count || 0
							}))
						);
					} else {
						// 如果没有找到项目，设置为空数组
						this.$set(this.companies[companyIndex], 'projects', []);
					}
				},
				(err) => {
					this.$set(this.companies[companyIndex], 'projects', []);
				},
				() => {
					// 关闭加载状态
					this.$set(this.companies[companyIndex], 'loading', false);
				}
			);
		},

		// 获取项目状态代码
		getProjectStatusCode(status) {
			const statusMap = {
				0: 'pending', // 待审核
				1: 'active', // 已激活/启用
				2: 'closed', // 已关闭/禁用
				3: 'rejected' // 已拒绝
			};
			return statusMap[status] || 'pending';
		},

		// 生成项目邀请二维码
		generateQrCode(projectId) {
			// 找到当前项目信息并保存
			this.currentProject = this.findProjectById(projectId);

			// 显示加载中
			uni.showLoading({
				title: '生成中...',
				mask: true
			});

			this.$request.generateQrCode(
				{
					project_id: projectId
				},
				(res) => {
					// 设置二维码URL
					this.qrCodeUrl = res.project_qrcode;

					// 显示二维码弹窗
					this.showQrCode = true;
				}
			);
		},

		// 查找项目信息
		findProjectById(projectId) {
			for (const company of this.companies) {
				if (company.projects && company.projects.length > 0) {
					const project = company.projects.find((p) => p.project_id === projectId);
					if (project) {
						return project;
					}
				}
			}
			return null;
		},

		// 关闭二维码弹窗
		closeQrCode() {
			this.showQrCode = false;
			this.currentProject = null;
		},

		// 保存二维码图片
		saveQrCode() {
			if (!this.qrCodeUrl) {
				uni.showToast({
					title: '二维码URL为空',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({
				title: '保存中...',
				mask: true
			});

			// 下载图片
			uni.downloadFile({
				url: this.qrCodeUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						// 保存图片到相册
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.hideLoading();
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								});
							},
							fail: (err) => {
								uni.hideLoading();

								// 判断是否是权限问题
								if (err.errMsg.indexOf('auth deny') > -1) {
									uni.showModal({
										title: '提示',
										content: '需要您授权保存图片到相册',
										confirmText: '去设置',
										success: (res) => {
											if (res.confirm) {
												// 打开设置页面
												uni.openSetting();
											}
										}
									});
								} else {
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									});
								}
							}
						});
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '下载图片失败',
							icon: 'none'
						});
					}
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast({
						title: '下载图片失败',
						icon: 'none'
					});
				}
			});
		},

		// 查看项目详情
		viewProjectDetail(enterpriseId, projectId) {
			uni.navigateTo({
				url: `/pages/project/detail?enterprise_id=${enterpriseId}&project_id=${projectId}`
			});
		},

		// 查看邀请记录
		viewInviteRecords(enterpriseId, projectId) {
			uni.navigateTo({
				url: `/pages/project/records?enterprise_id=${enterpriseId}&project_id=${projectId}`
			});
		},

		// 扫码绑定企业(企业邀请渠道绑定企业)
		scanQrCode() {
			wx.scanCode({
				scanType: ['wxCode'],
				success: (res) => {
					if (res.path && res.path.indexOf('scene=') != -1 && res.path.split('scene=').length >= 2) {
						// const decodedData = atob(res.rawData); // Base64 解码
						// console.log('解码结果:', decodedData);
						const queryStr = decodeURIComponent(res.path.split('scene=')[1]);
						const obj = _.chain(queryStr)
							.split('&')
							.map((param) => {
								const [key, val] = param.split('=');
								return [
									decodeURIComponent(key),
									val ? decodeURIComponent(val) : null // 处理空值
								];
							})
							.fromPairs()
							.value();
						// 绑定企业
						this.joinComp(obj.keyword);
					} else {
						uni.showToast({
							title: '无效的二维码',
							icon: 'none',
							duration: 1500,
							mask: true
						});
					}
				}
			});
		},

		// 绑定企业
		bindEnterprise(enterpriseId) {
			this.$request.bindEnterprise(
				{
					enterprise_id: enterpriseId
				},
				(res) => {
					uni.showToast({
						title: '绑定企业成功',
						icon: 'success'
					});

					// 重新加载数据
					setTimeout(() => {
						this.enterpriseListLoaded = false; // 重置加载标记
						this.loadData();
					}, 1500);
				}
			);
		}
	}
};
</script>

<style lang="scss" scoped>
// 引入sass样式变量(本来想全局引入，但是不成功，以后有空再解决)
@import '@/static/scss/variables.scss';

.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f7f8fa;
	font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
		'Helvetica Neue', sans-serif;
}

/* 搜索栏样式 */
.search-bar {
	padding: 12px 16px;
	background-color: #fff;
}

.search-input {
	display: flex;
	align-items: center;
	height: 36px;
	background-color: #f5f5f5;
	border-radius: 18px;
	padding: 0 12px;

	.iconfont {
		color: #999;
		margin-right: 2vw;
	}
}

.search-input .icon-search {
	font-size: 16px;
	margin-right: 8px;
	color: #999;
}

.search-input input {
	flex: 1;
	border: none;
	background: transparent;
	font-size: 14px;
	color: #333;
	outline: none;
}

/* 绑定企业按钮样式 */
.bind-company-btn {
	margin: 16px;
	height: 120px;
	background-color: $colorPrimary;
	border-radius: 12px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	color: #fff;
	box-shadow: 0 4px 12px rgba(64, 128, 255, 0.2);
	transition: all 0.2s ease;
}

.bind-company-btn:active {
	transform: scale(0.98);
	box-shadow: 0 2px 8px rgba(64, 128, 255, 0.2);
}

.bind-icon {
	width: 60px;
	height: 60px;
	background-color: #fff;
	border-radius: 30px;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-bottom: 12px;
}

.icon-group {
	display: flex;
	justify-content: center;
	align-items: center;
	width: 24px;
	height: 24px;

	.iconfont {
		color: $colorPrimary;
		font-size: 48rpx;
	}
}

.bind-text {
	font-size: 16px;
	font-weight: 500;
}

/* 企业列表样式 */
.company-list-container {
	flex: 1;
	padding: 0 16px;
	overflow-y: auto;
}

.company-list-title {
	font-size: 16px;
	color: #333;
	font-weight: 500;
	margin-bottom: 12px;
}

.company-list {
	background-color: #fff;
	border-radius: 8px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
	margin-bottom: 20px;
}

.company-item {
	display: flex;
	flex-direction: column;
	border-bottom: 1px solid #f0f0f0;
}

.company-item:last-child {
	border-bottom: none;
}

.company-header {
	display: flex;
	align-items: center;
	padding: 16px;
	transition: background-color 0.2s ease;
}

.company-header:active {
	background-color: #f9f9f9;
}

.company-icon {
	width: 40px;
	height: 40px;
	border-radius: 4px;
	background-color: $colorPrimaryLight3;
	display: flex;
	justify-content: center;
	align-items: center;
	margin-right: 12px;
}

.company-icon .icon-qiye {
	font-size: 20px;
	color: $colorPrimary;
}

.company-icon.disabled {
	background-color: #f5f5f5;
}

.company-icon.disabled .icon-qiye {
	color: #999;
}

.company-info {
	flex: 1;
}

.company-name-container {
	display: flex;
	align-items: center;
}

.company-name {
	font-size: 15px;
	color: #333;
	font-weight: 500;
}

.status-tag {
	font-size: 12px;
	color: #ff6340;
	background-color: #fff5f0;
	padding: 2px 6px;
	border-radius: 4px;
	margin-left: 8px;
}

.project-count {
	font-size: 13px;
	color: #999;
	margin-top: 4px;
}

.arrow-right {
	color: #ccc;
	transition: transform 0.2s ease;
}

.arrow-down {
	transform: rotate(90deg);
}

.arrow-right .icon-arrow-right,
.arrow-down .icon-arrow-down {
	font-size: 16px;
}

/* 项目列表样式 */
.project-list {
	background-color: #f9f9f9;
	border-top: 1px solid #f0f0f0;
}

/* 加载中样式 */
.loading-projects {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 24px 0;
}

.loading-spinner {
	width: 24px;
	height: 24px;
	border: 2px solid $colorPrimaryLight2;
	border-radius: 50%;
	border-top-color: $colorPrimary;
	animation: spin 0.8s linear infinite;
	margin-bottom: 8px;
}

@keyframes spin {
	to {
		transform: rotate(360deg);
	}
}

.loading-text {
	font-size: 14px;
	color: #999;
}

.project-item {
	padding: 16px;
	border-bottom: 1px solid #f0f0f0;
}

.project-item:last-child {
	border-bottom: none;
}

.project-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 8px;
}

.project-name {
	font-size: 14px;
	color: #333;
	font-weight: 500;
	display: flex;
	align-items: center;

	.name-content {
		max-width: 50vw;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
}

.project-people {
	display: flex;
	align-items: center;
	font-size: 12px;
	color: #666;
}

.project-actions {
	display: flex;
	gap: 8px;
}

.btn-action {
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12px;
	border-radius: 1vw;
	padding: 2vw 3vw calc(2vw + 1px) 3vw;
	width: calc((100vw - 10vw * 3) / 3);
}

.btn-record {
	border: 1px solid $colorPrimaryLight2;
	box-sizing: border-box;
	background-color: $colorPrimaryLight3;
	color: $colorPrimary;
}

.btn-generate {
	border: 1px solid $colorPrimary;
	box-sizing: border-box;
	color: $colorPrimary;
}

.btn-detail {
	background-color: $colorPrimary;
	color: #fff;
}

.empty-projects {
	padding: 20px 16px;
	display: flex;
	justify-content: center;
	align-items: center;
}

.empty-projects .empty-text {
	font-size: 14px;
	color: #999;
}

/* 空列表状态 */
.empty-list {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 48px 0;
	background-color: #fff;
	border-radius: 8px;
	margin-bottom: 20px;
}

.empty-icon {
	margin-bottom: 16px;

	image {
		width: 60vw;
		height: calc(60vw * 511 / 934);
	}
}

.empty-text {
	font-size: 14px;
	color: #999;
}

/* 二维码弹窗样式 */
.qrcode-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 999;
}

.modal-mask {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 80%;
	max-width: 600rpx;
	background-color: #fff;
	border-radius: 12px;
	padding: 24px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-title {
	font-size: 18px;
	font-weight: 600;
	text-align: center;
	margin-bottom: 16px;
	color: #333;
}

.qrcode-info {
	text-align: center;
	margin-bottom: 16px;
}

.qrcode-info .project-name {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	margin-bottom: 4px;
	display: flex;
	justify-content: center;
}

.qrcode-info .enterprise-name {
	font-size: 14px;
	color: #666;
}

.qrcode-box {
	width: 200px;
	height: 200px;
	margin: 0 auto;
	background-color: #f5f5f5;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 8px;
}

.qrcode-box image {
	width: 90%;
	height: 90%;
}

.qrcode-tips {
	text-align: center;
	font-size: 13px;
	color: #999;
	margin: 16px 0;
}

.modal-actions {
	display: flex;
	justify-content: space-between;
	margin-top: 8px;
}

.action-btn {
	flex: 1;
	height: 40px;
	line-height: 40px;
	text-align: center;
	border-radius: 20px;
	font-size: 14px;
	font-weight: 500;
	margin: 0 8px;
}

.action-btn.cancel {
	background-color: #f5f5f5;
	color: #666;
}

.action-btn.confirm {
	background-color: $colorPrimary;
	color: #fff;
}
</style>
